package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckItemService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Service(interfaceClass = CheckItemService.class)
public class CheckItemServiceImpl implements CheckItemService {


    @Autowired
    private CheckItemMapper checkItemMapper;

    /**
     * 新增检查项
     *
     * @param checkItem
     */

    @Override
    public void add(CheckItem checkItem) {
        checkItemMapper.add(checkItem);
    }

    /**
     * 通过页数据获取该页数据
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {

        //使用mybatis的分页插件,查询语句会自动拦截，所以顺序不会变
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        List<CheckItem> checkItemList = checkItemMapper.findByCondition(queryPageBean.getQueryString());
        PageInfo<CheckItem> pageInfo = new PageInfo<>(checkItemList);

        return new PageResult(pageInfo.getTotal(), pageInfo.getList());
    }

    /**
     * 根据id删除项目
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //通过检查项的id查询是否在中间表中被引用
        Integer count = checkItemMapper.findCountByCheckItemId(id);
        if (count>0){
            //抛出运行时异常，已经被引用
            throw  new RuntimeException(MessageConstant.CHECKITEM_IS_QUOTED);
        }
        checkItemMapper.deleteById(id);
    }

    /**
     * 根据id查询项目
     *
     * @param id
     */
    @Override
    public CheckItem findById(Integer id) {
        return checkItemMapper.findById(id);
    }

    /**
     * 编辑检查项
     *
     * @param checkItem
     */
    @Override
    public void edit(CheckItem checkItem) {
        checkItemMapper.edit(checkItem);
    }

    /**
     * 返回所有的检查项的集合
     *
     * @return
     */
    @Override
    public List<CheckItem> findAll() {
        return checkItemMapper.findAll();
    }

}
